package com.myjoje.controller.tencent;

import com.alibaba.fastjson.JSON;
import com.myjoje.config.shiro.ShiroUtil;
import com.myjoje.util.OkHttpUtil;
import okhttp3.Response;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.StringReader;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 微信接口测试
 */
@RestController
@RequestMapping("/tencent/wechat")
public class WeChatController {

    private String token = "wechat";

    /*响应微信验证*/
    @GetMapping("/validate")
    public void validate(HttpServletResponse response, String signature, String timestamp,
                         String nonce, String echostr) throws IOException {
        //1）将token、timestamp、nonce三个参数进行字典序排序
        String[] arr = {token, timestamp, nonce};
        Arrays.sort(arr);

        //2）将三个参数字符串拼接成一个字符串进行sha1加密
        String content = arr[0].concat(arr[1]).concat(arr[2]);

        String sha1 = ShiroUtil.getSha1(content);

        //3）开发者获得加密后的字符串可与signature对比
        if (sha1.equals(signature)) {
            response.getWriter().println(echostr);
        }
    }

    /*消息处理*/
    @PostMapping("/validate")
    public void handleMessage(HttpServletResponse response, @RequestBody String msg) throws Exception {
        SAXReader reader = new SAXReader();
        Document document = reader.read(new StringReader(msg));
        List<Element> elements = document.getRootElement().elements();

        Map map = new HashMap();
        for (Element element : elements) {
            String text = element.getText();
            String name = element.getName();
            if ("FromUserName".equals(name)) {
                map.put("fromUser", text);
            } else if ("Content".equals(name)) {
                map.put("content", text);
            }
        }
        System.out.println(map);
        response.setCharacterEncoding("utf-8");
        response.getWriter().println("<xml>" +
                "<ToUserName><![CDATA[oA2Odwfmidf8DOCXAhm2By8MF5f0]]></ToUserName>" +
                "<FromUserName><![CDATA[gh_c15ed287e734]]></FromUserName>" +
                "<CreateTime>1571380014</CreateTime>" +
                "<MsgType><![CDATA[text]]></MsgType>" +
                "<Content><![CDATA[你好]]></Content>" +
                "</xml>");
    }

    //获取AccessToken
    @RequestMapping("getAccessToken")
    public Object getAccessToken() throws IOException {
        String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&" +
                "appid=wx4ce1b3e266d91de6&secret=af9530542bdc16e3a698d9acf05f4613";
        Response response = OkHttpUtil.get(url);
        return JSON.parse(response.body().string());
    }

    /*获取微信callback IP地址*/
    //获取AccessToken
    @RequestMapping("/getCallbackIp")
    public Object getCallbackIp(String accessToken) throws IOException {
        String url = "https://api.weixin.qq.com/cgi-bin/getcallbackip?access_token=" + accessToken;
        //创建请求
        Response response = OkHttpUtil.get(url);
        return JSON.parse(response.body().string());
    }


    @RequestMapping("/addButton")
    public void addButton(String accessToken) throws IOException {
        String url = " https://api.weixin.qq.com/cgi-bin/menu/create?access_token=" + accessToken;

        String rediredtUrl = "https://open.weixin.qq.com/connect/oauth2/authorize?" +
                "appid=wx4ce1b3e266d91de6&" +
                "redirect_uri=http://www.myjoje.cn/test/test&" +
                "response_type=code&" +
                "scope=snsapi_base&" +
                "state=123#wechat_redirect";
        String btn = "{" +
                "\"button\": [" +
                "        {" +
                "            \"name\": \"扫码\", " +
                "            \"sub_button\": [" +
                "                {" +
                "                    \"type\": \"scancode_waitmsg\", " +
                "                    \"name\": \"扫码带提示\", " +
                "                    \"key\": \"rselfmenu_0_0\", " +
                "                    \"sub_button\": [ ]" +
                "                }, " +
                "                {" +
                "                    \"type\": \"view\", " +
                "                    \"name\": \"搜索\", " +
                "                    \"url\": \"" + rediredtUrl + "\", " +
                "                    \"key\": \"rselfmenu_0_1\", " +
                "                    \"sub_button\": [ ]" +
                "                }" +
                "            ]" +
                "        }" +
                "]" +
                "}";
        Response response = OkHttpUtil.postJson(url, btn);
        System.out.println(response);
    }

    @RequestMapping("/sendTemplateMsg")
    public void sendTemplateMsg(String accessToken) throws IOException {
        String url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + accessToken;
        String msg = "{" +
                "           \"touser\":\"oA2Odwft_QDvq7wHZpDZqTEdoj8U\"," +
                "           \"template_id\":\"OTB1d5aIlIOJZNPtWb9rIsauha-X4vB5c5i1OBzCrGY\"," +
                "           \"url\":\"http://weixin.qq.com\",  " +
                "           \"data\":{" +
                "                   \"result\": {" +
                "                       \"value\":\"恭喜你购买成功！\"," +
                "                       \"color\":\"#173177\"" +
                "                   }" +
                "           }" +
                "       }";

        Response response = OkHttpUtil.postJson(url, msg);
        System.out.println(response.body().string());
    }

    @RequestMapping("/getUserInfo")
    public Object getUserInfo(String accessToken, String openId) throws IOException {
        String url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=" + accessToken + "&openid=" + openId;

        Response response = OkHttpUtil.get(url);
        return JSON.parse(response.body().string());
    }


}
